import React, {useState, useRef, useContext, useCallback} from 'react';
import Select from '../components/Select';

import "./assets/canvas.css";

export default {
  title: '4 - Select',
  component: Select,
	decorators: [
		(Story) => (
			<div className="canvas" style={{width: 400}}>
				<Story/>
			</div>
		),
	],
	argTypes: {
    color: {options: ['red', 'blue', 'yellow', 'orange', 'purple', 'cyan', 'base03']},
    isDisabled: {
      type: 'boolean',
      defaultValue: false
    }
	},
}

const buildCascadedOptions = (times) => {

  const suggs = {};

  for (let i = 0; i < times; i++) {

    let curr = suggs;
    while (true) {
      
      if (curr === undefined) {
        break;
      }

      const keys = Object.keys(curr);

      if (keys.length === 0 || Math.random() < 0.05) {
        const key = Math.random().toString(35).slice(2, 10);
        curr[key] = {};
        break;
      } else {
        curr = curr[keys[Math.floor(Math.random() * keys.length)]];
      }
    }
  }

  return suggs;
}

const getSuggs = (suggTree, path) => {
  let curr = suggTree;
  for (let pathSeg of path) {
    if(pathSeg === '') {
      break;
    }
    curr = curr[pathSeg];
    if (curr === undefined) {
      break;
    }
  }

  console.log(path, curr);
  if (curr === undefined) {
    return ['No suggestions']
  } else {
    const keys = Object.keys(curr);
    if (keys.length === 0) {
      return ['No suggestions']      
    } else {
      return keys;
    }
  }
}

const suggTree = buildCascadedOptions(400);

const Template = (args) => {

  const [value, setValue] = useState('');
  const [suggs, setSuggs] = useState(getSuggs(suggTree, ''));

  const onChange = useCallback((e) => {
    const value = e.target.value;
    setValue(value);

    const path = value.split('/');
    path.pop();
    setSuggs(getSuggs(suggTree, path));
  }, [value]);

  const onSelectOption = useCallback((e) => {
    
    const newValString = value.replace(/(\/|^)[^\/]*$/, `$1${e.target.value}/`);

    setValue(newValString);

    const path = newValString.split('/');
    setSuggs(getSuggs(suggTree, path));
  }, [suggs]);

  return <div style={{position: 'relative', width: 300, margin: 10}}>
    <div style={{position: 'relative'}}> Input label </div>
    <Select {...{...args, value, suggs, onChange, onSelectOption}} />
  </div>;
}

export const Default = Template.bind({});

Default.args = {
	
}
